package com.practice.jwt;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

@Component
public class JwtUtils {

    //密钥
    private final String secret = "practice";
    //过期时间
    private final Long expiration = (long) (3600 * 1000 * 24);

    /**
     * 生成token
     */
    public String generateToken(Map<String, Object> map) {
        Date expirationDate = new Date(System.currentTimeMillis() + expiration);
        map.put("expire_time", expirationDate);
        return Jwts.builder().setClaims(map).setExpiration(expirationDate).signWith(SignatureAlgorithm.HS512, secret).compact();
    }

    /**
     * 解析token获取用户
     */
    public String getAccountNameFromToken(String token) {
        String accountName;
        try {
            Claims claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
            accountName = claims.getSubject();
        } catch (Exception e) {
            accountName = null;
        }
        return accountName;
    }
}
